import React, { useEffect, useRef, useState } from "react";
import { useCountdown } from "../../../context/MemberContext";
import { useNavigate, useLocation } from "react-router-dom";
import { Modal, NavBar, Toast, Image as MyImage, Button } from "antd-mobile";
import { ReactComponent as TimingIcon } from "../../../asset/imgs/timing.svg";
import "./style.scss";

const iconColor = getComputedStyle(document.documentElement)
  .getPropertyValue("--themeColor")
  .trim();

const formatTime = (remainingTime: any) => {
  const minutes = Math.floor(remainingTime / (1000 * 60));
  const seconds = Math.floor((remainingTime % (1000 * 60)) / 1000);
  const milliseconds = Math.floor((remainingTime % 1000) / 10);
  return `${minutes.toString().padStart(2, "0")}:${seconds
    .toString()
    .padStart(2, "0")}`;
};

export default function ActivityTiming() {
  const location: any = useLocation();
  const navigate: any = useNavigate();
  const { setCountdowns, startCountdown, stopCountdown }: any = useCountdown();
  const [remainingTime, setRemainingTime] = useState<any>(0);
  const [isLoaded, setLoaded] = useState(false);
  const timeRef: any = useRef();
  const detail = location?.state?.detail;
  const {
    memberName,
    memberId,
    memberFormulPhoto,
    eventId,
    customerId,
    goodsId,
    timingDuration,
    goodsName,
    number,
  }: any = location?.state?.detail;
  const timing = location?.state?.timing;
  const savedCountdowns: any = localStorage.getItem("countdowns");
  const countdowns: any =  savedCountdowns ? JSON.parse(savedCountdowns) : {};

  const currentId = `${eventId}_${memberId}`;
  const idStorage = localStorage.getItem("id");
  if (!idStorage) { localStorage.setItem('id', currentId); }
  const id: any = currentId || idStorage;
  const goodsNameShow = goodsName || countdowns[id]?.goodsName;
  const numberShow = number || countdowns[id]?.number;
  const timingDurationShow = timingDuration || countdowns[id]?.timingDuration;
  const end = countdowns[id]?.end;

  useEffect(() => {
    const rest = countdowns[id];
    setCountdowns((prev: any) => {
      const newCountdowns = {
        ...prev,
        [id]: { ...rest, end: false },
      };
      localStorage.setItem('countdowns', JSON.stringify(newCountdowns))
      return newCountdowns;
    });
    if (!countdowns?.[id]?.endTime || countdowns?.[id]?.endTime <= 0) {
      setLoaded(true);
      return;
    } else {
      setLoaded(true);
      handleCutdowns(countdowns?.[id]?.endTime);
    }
    // return () => {
    //   clearInterval(timeRef.current);
    // };
  }, []);

  useEffect(()=>{
    return () => {
      clearInterval(timeRef.current);
    };
  },[])

  const handleCutdowns = (endTime = Date.now() + timingDurationShow * number * 1000) => {
    timeRef.current = setInterval(async () => {
       if (endTime >= Date.now()) {
        // 正在计时
        const remainingTime = formatTime(endTime - Date.now());
        setRemainingTime(remainingTime);
        setLoaded(true);
      } else if (endTime === 0 || endTime < Date.now()) {
        // 计时到时间，状态为超时，关闭定时器，删除排队人员
        // setCountdowns((prev: any) => {
        //   const newCountdowns = {
        //     ...prev,
        //     [id]: {
        //       ...countdowns[id],
        //       endTime: 0, visible: true, end: true,
        //     },
        //   };
        //   return newCountdowns;
        // });
        // navigate("/activity/participates", {
        //   state: { detail: { ...detail, timing } },
        // });
        clearInterval(timeRef.current);
        stopCountdown(eventId, memberId);
        setRemainingTime(0);
        setLoaded(true);
      }
    }, 10);
  };

  const back = () => {
    navigate("/activity/participates", {
      state: { detail: { ...detail, timing } },
    });
  };

  return (
    <div className="container_activity_timing">
      <NavBar
        style={{
          "--border-bottom": "1px #eee solid",
        }}
        onBack={() => back()}
      >
        排队详情
      </NavBar>
      <div className="activity_public">
        <li className="that_item">
          <MyImage
            src={memberFormulPhoto}
            fit="cover"
            width="4rem"
            height="4rem"
            lazy={true}
          />
          <div className="item_content_wraper">
            <div className="name">{memberName}</div>
            <div className="center">
              <div className="type">
                <div>核销类型：</div>
                <div>{goodsNameShow}</div>
              </div>
              <div className="num">
                <div>核销张数：</div>
                <div>{numberShow}</div>
              </div>
            </div>
          </div>
        </li>
        {isLoaded ? <div>
          <div className="total_time">
            <span>总时长：</span>
            {formatTime(timingDurationShow * numberShow * 1000)}
          </div>
          <div
            className="start_time"
            onClick={async () => {
              if (countdowns?.[id]?.endTime) {
                Toast.show("当前正在计时，请勿重复操作");
                return;
              }
              if (end) {
                Toast.show("当前排队已结束，请返回重试");
                return;
              }

              const flag = await startCountdown(
                eventId,
                memberId,
                customerId,
                timingDuration,
                number,
                goodsId,
                goodsName,
                goodsNameShow,
                numberShow
              );
              if (flag) {
                handleCutdowns();
              }
            }}
          >
            <TimingIcon width={50} height={50} fill={iconColor} />

            {remainingTime ? (
              <>
                <div className="timing">{remainingTime}</div>
                <span>剩余时间</span>
              </>
            ) : (
              "开始计时"
            )}
          </div>
          <div className="end_time">
            <Button
              onClick={() => {
                console.log(countdowns);
                if (countdowns?.[id]?.endTime === 0 || countdowns?.[id]?.endTime < Date.now()) {
                  return;
                } else {
                  clearInterval(timeRef.current);
                  stopCountdown(eventId, memberId);
                  setRemainingTime(0);
                }
              }}
            >
              结束计时
            </Button>
          </div>
        </div> : <></>}
      </div>

      {countdowns?.[id]?.visible && (
        <Modal
          visible={countdowns?.[id]?.visible}
          content="当前粉丝特典券使用时间已超时，请催促粉丝让位"
          // content="当前计时已结束，请返回重新操作!"
          actions={[
            {
              key: "ok",
              text: "我知道了",
              primary: true,
              onClick() {
                const rest = countdowns[id];
                setCountdowns((prev: any) => {
                  const newCountdowns = {
                    ...prev,
                    [id]: { ...rest, visible: false },
                  };
                  localStorage.setItem("countdowns", JSON.stringify(newCountdowns)); // 保存到 localStorage
                  return newCountdowns;
                });
                navigate("/activity/queue", {
                  state: { detail },
                });
              },
            },
          ]}
        />
      )}
    </div>
  );
}
